<template>
	<view class="datePicker">
	<view class="selectDate" @tap="openDatePicker">
		<text>{{dateRangeList.length > 0 ?  dateRangeList[0] : tabList[0].dateTime}}</text>
		<text>至</text>
		<text>{{dateRangeList.length > 1 ?  dateRangeList[1] : tabList[1].dateTime}}</text>
	</view>
	<uni-popup ref="popup" type="bottom" background-color="#fff" borderRadius="32rpx 32rpx 0 0" class="popupSts">
	<view class="pickerWrap">
		<view class="head">
			<text>选择时间</text>
			<image src="../../static/icon/close.png" mode="" @tap="close"></image>
		</view>
		<view class="mainControll">
			<view class="tabList">
				<view v-for="(item,index) in tabList" :key="index" @tap="select(index)" :class="{activeTabs:index === selectActive}">
					<text>{{item.title}}</text>
					<text>{{item.dateTime}}</text>
				</view>
			</view>
			<view class="pickWrap">
			<picker-view
			  class="picker-view" 
			  :value="pickerValue" 
			  @change="onPickerChange"
			  @cancel="showPicker = false"
			>
			  <picker-view-column style="flex: 2;">
			    <view 
			      v-for="(year, index) in years" 
			      :key="index" 
			      class="picker-item"
			    >
			      {{ year }}年
			    </view>
			  </picker-view-column>
			  <picker-view-column style="flex: 1;">
			    <view 
			      v-for="(month, index) in months" 
			      :key="index" 
			      class="picker-item"
			    >
			      {{ month }}月
			    </view>
			  </picker-view-column>
			  <picker-view-column style="flex: 1;">
			    <view 
			      v-for="(day, index) in days" 
			      :key="index" 
			      class="picker-item"
			    >
			      {{ day }}日
			    </view>
			  </picker-view-column>
			</picker-view>	
			</view>
			<!-- 按钮确认 -->
			<view class="btn_grounp">
				<view class="reset" @tap="reset">
					重置
				</view>
				<view class="confirm" @tap="confirm">
					确认选择
				</view>
			</view>
		</view>
	</view>
	</uni-popup>	
	</view>

</template>

<script setup>
import {defineEmits,onMounted,ref, watch} from 'vue'
const tabList = ref([])
const dateRangeList = ref([])
const formatTime = (timeCash)=>{
	const year = timeCash.getFullYear(); // 获取完整的年份（如2025）
	const month = String(timeCash.getMonth() + 1).padStart(2); // 获取月份（0-11），需要加1并补零
	const day = String(timeCash.getDate()).padStart(2); // 获取日期并补零
	// 格式化为 YY年MM月DD日
	const formattedDate = `${year}年${month}月${day}日`;
	return formattedDate
}
// 获取当前时间往前推一年时间
const getCurrentTimeToPresent = ()=>{
	// 获取当前时间
	const now = new Date();
	const oneYearAgo = new Date(now.setFullYear(now.getFullYear() - 1));
	tabList.value = [
	{title:"起始日期",dateTime:formatTime( oneYearAgo)},
	{title:"截止日期",dateTime:formatTime(new Date())}
     ]
	dateRangeList.value = [
		formatTime(oneYearAgo),
		formatTime(new Date())
	]
}
getCurrentTimeToPresent()
// 格式化时间

const selectActive = ref(0) //选中的tabs
const select = (index)=>{
	// 当全部选中的时候才允许手动切换
	const flag = tabList.value.every(val=>{
	  return val.dateTime.includes('-')
	})
	if(!flag){
	selectActive.value = index
	// 回显选中的日期
	const dateStr = tabList.value[index].dateTime
	let result = dateStr.match(/\d+/g);
	if(result){
		const yearIndex = years.value.findIndex(val=>val === result[0] *1)
		const monthIndex = months.value.findIndex(val=>val === result[1] *1)
		pickerValue.value = [yearIndex,monthIndex,result[2]*1 -1]
	}else{
		pickerValue.value = [0,0,0]
	}
	}

}
const showPicker = ref(false)
const pickerValue = ref([0, 0, 0])
const years = ref([]) // 年份列表
const months = ref([]) // 月份列表
const days= ref([]) // 日期列表
    // 初始化年份列表
 const initYears=()=> {
      const currentYear = new Date().getFullYear();
      for (let year = currentYear - 2; year <= currentYear + 2; year++) {
       years.value.push(year);
      }
    }

    // 初始化月份列表
  const initMonths=()=>{
      for (let month = 1; month <= 12; month++) {
        months.value.push(month);
      }
    }

    // 初始化日期列表
 const initDays=()=>{
      // 默认为当前月份的日期
      const currentYear = new Date().getFullYear();
      const currentMonth = new Date().getMonth() + 1;
      days.value = getDaysInMonth(currentYear, currentMonth);
    }

    // 获取某年某月的天数
 const getDaysInMonth=(year, month)=>{
      const date = new Date(year, month, 0);
      return date.getDate();
    }

    // 选择器值改变时的处理函数
  const onPickerChange=(e)=> {
      const value = e.detail.value;
      pickerValue.value = value;
      // 更新日期列表
      const selectedYear = years.value[value[0]];
      const selectedMonth = months.value[value[1]];
      days.value = getDaysInMonth(selectedYear, selectedMonth);
    }

	initYears()
	initMonths()
	initDays()
const confirm = ()=>{
	let timer = setTimeout(()=>{
		const str = pickerValue.value.reduce((curr,val,index)=>{
			switch(index){
				case 0:
				curr += years.value[val] + '年'
				break;
				case 1:
				curr += months.value[val] + '月'
				break;
				case 2:
				curr += val+ 1 + '日'
				break;
			}
			return curr
		},"")
		tabList.value[selectActive.value].dateTime =  str
		if(selectActive.value === 0){
			selectActive.value = 1
		}else{
			
		}
		clearTimeout(timer)
		const flag = tabList.value.some(val=>{
		  return val.dateTime.includes('-')
		})
		if(!flag){

		if(compare(0) > compare(1)){
			uni.showToast({
				icon:'error',
				title:"开始时间不能大于截止时间"
			})
		}else{
			//全部选择完毕
			dateRangeList.value = tabList.value.reduce((curr,val)=>{
				curr.push(val.dateTime)
				return curr
			},[])
			close()
		}
		}
	},800)
 
}
const compare = (index)=>{
	const dateStr = tabList.value[index].dateTime
    const [y, m, d] = dateStr.match(/\d+/g);
    return new Date(`${y}-${m}-${d}`);
  }
// 打开日期选择器
const popup = ref(false)
const openDatePicker = ()=>{
	select(0)
	popup.value.open()
}
const close = ()=>{
	popup.value.close()
}
// 重置结果
const reset = ()=>{
	dateRangeList.value = []
	selectActive.value = 0
	const dateStr = tabList.value[selectActive.value].dateTime
	let result = dateStr.match(/\d+/g);
	if(result){
		const yearIndex = years.value.findIndex(val=>val === result[0] *1)
		const monthIndex = months.value.findIndex(val=>val === result[1] *1)
		pickerValue.value = [yearIndex,monthIndex,result[2]*1 -1]
		}
	getCurrentTimeToPresent()
}
const emits = defineEmits(["changeTime"])
watch(()=>dateRangeList.value,(val)=>{
	const newVal = val.map(item=>{
	 	item =  item.match(/\d+/g).join("-")
		return item
	})
	emits("changeTime",newVal)
},{
	immediate:true,
	deep:true
})
</script>

<style scoped lang="scss">
.datePicker{
	.selectDate{
		display: flex;
		justify-content: space-between;
		margin-bottom: 35rpx;
		text{
			&:first-child{
				color: #66686A;
			}
			&:nth-child(2){
				color: #BBC0C9;
			}
			&:last-child{
				color: #66686A;
			}
		}
	}
	.pickerWrap{
		padding: 32rpx 0 0 0rpx;
		margin-bottom: 100rpx;
		.head{
			padding: 0 32rpx;
			display: flex;
			justify-content: space-between;
			>text{
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #00041A;
			}
			>image{
			width: 32rpx;
			height: 32rpx;
			}
		}
		.mainControll{
			margin-top: 35rpx;
			.tabList{
				display: flex;
				border-bottom: 1rpx solid #E3EBF2;
				>view{
					flex: 1;
					text-align: center;
					padding-bottom: 32rpx !important;
					text{
						display: block;
						font-family: PingFangSC, PingFang SC;
						color: #686A73;
						&:first-child{
							font-weight: 500;
							font-size: 28rpx;
							line-height: 50rpx;
						}
						&:last-child{
							font-weight: 400;
							font-size: 24rpx;
							line-height: 33rpx;
						}
					}
				}
				.activeTabs{
					position: relative;
					text{
						color: #00041A;
					}
					&::after{
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						content: "";
						width: 48rpx;
						height: 8rpx;
						background: #0D53FE;
						border-radius: 4rpx;
					}
				}
			}
		}
	}
	.pickWrap{
		position: relative;
		padding: 32rpx 32rpx 0 ;
		margin-bottom: 32rpx;
		&::after{
			content: "";
			width: 1rpx;
			height: 340rpx;
			background-color: #E3EBF2;
			position: absolute;
			left: 50%;
			top: 0;
			transform: translateX(-50%);
		}
		.picker-view{
			 height: 300rpx;
			 .picker-item {
			   text-align: center;
			   line-height: 40px;
			   font-size: 16px;
			 }
		}
	}
	.btn_grounp{
		display: flex;
		padding:0 32rpx;
		margin-bottom: 30rpx;
		>view{
			flex: 1;
			text-align: center;
			height: 100rpx;
			line-height:100rpx ;
			border-radius: 16rpx;
			background: #F0F5FF;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
		}
		.reset{
		margin-right: 24rpx;
			font-size: 32rpx;
			color: #0D53FE;
		}
		.confirm{
			background: #0D53FE;
			color: #FFFFFF;
		}
	}
}
</style>